package com.softlab.retailwholesalesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.softlab.retailwholesalesystem.entity.*;
import com.softlab.retailwholesalesystem.entity.VO.StatisticsGoodsVOEntity;
import com.softlab.retailwholesalesystem.mapper.*;
import com.softlab.retailwholesalesystem.service.IStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Array;
import java.util.ArrayList;
import java.util.List;

@Service
public class StatisticsServiceImpl extends ServiceImpl<StatisticsMapper, StatisticsEntity> implements IStatisticsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private OrderGoodsMapMapper orderGoodsMapMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StatisticsMapper mapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClientMapper clientMapper;

    /**
     * 初始化数据库内容
     */
    @Override
    public void init() {
        mapper.delete(null);

        List<GoodsEntity> goodsEntities = goodsMapper.selectList(null);
        for (GoodsEntity goods :
                goodsEntities) {

            if (goods.getIsDelete() == 1)
                continue;
            //对每一个未删除的goods按照id进行数据库查找

            StatisticsEntity statisticsEntity = new StatisticsEntity();
            Long goodsId = goods.getGoodsId();
            statisticsEntity.setGoodsId(goodsId);
            statisticsEntity.setGoodsPrice(goods.getaPrice());
            statisticsEntity.setIsDelete(0);
            statisticsEntity.setGoodsPic("");

            //查库存
            QueryWrapper<StoreEntity> storeEntityQueryWrapper = new QueryWrapper<>();
            storeEntityQueryWrapper.eq("is_delete", 0);
            storeEntityQueryWrapper.eq("goods_id", goodsId);
            List<StoreEntity> storeEntities = storeMapper.selectList(storeEntityQueryWrapper);
            int count = 0;
            for (StoreEntity store :
                    storeEntities) {
                count += store.getGoodsNumber();
            }
            statisticsEntity.setGoodsStored((long) count);

            //查销售、利润
            QueryWrapper<OrderGoodsMapEntity> goodsMapEntityQueryWrapper = new QueryWrapper<>();
            goodsMapEntityQueryWrapper.eq("is_delete", 0);
            goodsMapEntityQueryWrapper.eq("goods_id", goodsId);
            List<OrderGoodsMapEntity> orderGoodsMapEntities = orderGoodsMapMapper.selectList(goodsMapEntityQueryWrapper);
            count = 0;
            double profit = 0;
            double soldMoney = 0;

            for (OrderGoodsMapEntity orderGoodsMapEntity
                    : orderGoodsMapEntities) {

                Long orderId = orderGoodsMapEntity.getOrderId();
                OrderEntity order = orderMapper.selectById(orderId);

                //利润、销售金额
                if (order.getInOut() == 1) {
                    //售出订单
                    count += orderGoodsMapEntity.getGoodsNumber();
                    soldMoney += orderGoodsMapEntity.getGoodsNumber() * orderGoodsMapEntity.getSinglePrice();
                    profit += orderGoodsMapEntity.getGoodsNumber() * (orderGoodsMapEntity.getSinglePrice() - goods.getStockPrice());
                } else {
                    //退货订单
                    count -= orderGoodsMapEntity.getGoodsNumber();
                    soldMoney -= orderGoodsMapEntity.getGoodsNumber() * orderGoodsMapEntity.getSinglePrice();
                    profit -= orderGoodsMapEntity.getGoodsNumber() * (orderGoodsMapEntity.getSinglePrice() - goods.getStockPrice());

                }
            }
            statisticsEntity.setGoodsSold((long) count);
            statisticsEntity.setGoodsProfit(profit);
            statisticsEntity.setSoldMoney(soldMoney);

            statisticsEntity.setUnSoldMoney(statisticsEntity.getGoodsStored() * goods.getStockPrice());
            statisticsEntity.setPurchaseMoney(goods.getStockPrice() * (statisticsEntity.getGoodsSold() + statisticsEntity.getGoodsStored()));


            mapper.insert(statisticsEntity);
        }

    }

    @Override
    public List<StatisticsGoodsVOEntity> getAll(Wrapper<StatisticsEntity> queryWrapper) {
        List<StatisticsEntity> statisticsEntities = mapper.selectList(queryWrapper);
        List<StatisticsGoodsVOEntity> list = new ArrayList<>();
        for (StatisticsEntity entity
                : statisticsEntities) {
            StatisticsGoodsVOEntity statisticsGoodsVOEntity = new StatisticsGoodsVOEntity(entity);

            statisticsGoodsVOEntity.setGoodsName(goodsMapper.selectById(entity.getGoodsId()).getGoodsName());
            list.add(statisticsGoodsVOEntity);
        }

        return list;
    }

    @Override
    public List<StatisticsGoodsVOEntity> search(StatisticsEntity entity) {
        QueryWrapper<StatisticsEntity> wrapper = new QueryWrapper<>();

        if (entity.getStatisticsId() != null) wrapper.eq("statistics_id", entity.getStatisticsId());
        if (entity.getGoodsId() != null) wrapper.eq("goods_id", entity.getGoodsId());
        if (entity.getGoodsPrice() != null) wrapper.eq("goods_price", entity.getGoodsPrice());
        if (entity.getGoodsProfit() != null) wrapper.eq("goods_profit", entity.getGoodsProfit());
        if (entity.getGoodsSold() != null) wrapper.eq("goods_sold", entity.getGoodsSold());
        if (entity.getGoodsStored() != null) wrapper.eq("goods_stored", entity.getGoodsStored());
        wrapper.eq("is_delete", 0);

        List<StatisticsEntity> list = mapper.selectList(wrapper);
        ArrayList<StatisticsGoodsVOEntity> statisticsGoodsVOEntities = new ArrayList<>();
        for (StatisticsEntity entity1
                : list) {
            StatisticsGoodsVOEntity statisticsGoodsVOEntity = new StatisticsGoodsVOEntity(entity1);
            statisticsGoodsVOEntity.setGoodsName(goodsMapper.selectById(entity.getGoodsId()).getGoodsName());
            statisticsGoodsVOEntities.add(statisticsGoodsVOEntity);
        }

        return statisticsGoodsVOEntities;
    }

    @Override
    public List<Double> getStatusStatistics() {
        List<Double> list = new ArrayList<>();
        List<StatisticsEntity> statisticsEntities = mapper.selectList(null);
        double purchase = 0, sold = 0, unSold = 0, profit = 0;
        for (StatisticsEntity entity
                : statisticsEntities) {
            if (entity.getIsDelete() == 1)
                continue;

            purchase += entity.getPurchaseMoney();
            sold += entity.getSoldMoney();
            unSold += entity.getUnSoldMoney();
            profit += entity.getGoodsProfit();
        }

        list.add(purchase);
        list.add(sold);
        list.add(unSold);
        list.add(profit);
        return list;
    }

    @Override
    public List<WorkerStatistics> getWorkerStatistics(Average average) {
        Average avr = average;
        if (average == null) {
            avr = new Average(0.5, 0.2, 0.8);
        } else if (average.getWeight1() == null || average.getWeight2() == null || average.getWeight3() == null) {
            avr = new Average(0.5, 0.2, 0.8);
        } else if (average.getWeight1() == 0 || average.getWeight2() == 0 || average.getWeight3() == 0) {
            avr = new Average(0.5, 0.2, 0.8);
        }


        //销售数量、客户数量、销售金额
        //order 中的clientname 对应客户 计算销售金额和销售数量
        //先找销售员集合

        //注意更改成roleid的情况
        QueryWrapper<UserEntity> qw = new QueryWrapper<UserEntity>().eq("role_name", "销售员");
        qw.eq("is_delete", 0);
        List<UserEntity> userList = userMapper.selectList(qw);


        List<WorkerStatistics> workerStatistics = new ArrayList<>();

        if (userList.isEmpty()) {
            return null;
        }

        for (UserEntity user : userList) {
            WorkerStatistics specificWorker = getSpecificWorker(avr, user);
            if (specificWorker == null)
                continue;
            specificWorker.setValue(specificWorker.getWorkerName());
            workerStatistics.add(specificWorker);
        }

        //最后返回的统计结果
        return workerStatistics;
    }

    @Override
    public WorkerStatistics getSpecificWorker(Average avr, UserEntity user) {
        if (!user.getRoleName().equals("销售员"))
            return null;
        //销售员集合
        QueryWrapper<ClientEntity> qw1 = new QueryWrapper<>();
        qw1.eq("is_delete", 0);
        qw1.eq("worker_id", user.getUserId());

        List<ClientEntity> clientList = clientMapper.selectList(qw1);


        int clientNumber = clientList.size();
        if (clientNumber == 0) {

            return
                    new WorkerStatistics(
                            user.getUsername(),
                            0,
                            0,
                            0.0,
                            0.0,
                            null
                    )
                    ;

        }

        int num = 0;
        double profit = 0;
        for (ClientEntity client : clientList) {
            //销售员对应的客户集合
            QueryWrapper<OrderEntity> qw2 = new QueryWrapper<>();
            qw2.eq("is_delete", 0);
            qw2.eq("client_name", client.getClientName());

            List<OrderEntity> orderList = orderMapper.selectList(qw2);

            if (orderList.size() == 0) {
                // TODO: 2022/1/4
                continue;
            }

            for (OrderEntity order : orderList) {
                //客户对应的订单集合
                if (order.getIsDelete() == 1)
                    continue;

                QueryWrapper<OrderGoodsMapEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("is_delete", 0);
                queryWrapper.eq("order_id", order.getOrderId());
                //找到对应的订单项
                List<OrderGoodsMapEntity> mapList = orderGoodsMapMapper.selectList(queryWrapper);


                //销售单
                if (order.getInOut() == 1) {
                    profit += order.getOrderProfit();
                    for (OrderGoodsMapEntity map : mapList) {
                        num += map.getGoodsNumber();
                    }

                }

                //退货单
                if (order.getInOut() == 0) {
                    profit -= order.getOrderProfit();
                    for (OrderGoodsMapEntity map : mapList) {
                        num -= map.getGoodsNumber();
                    }

                }
            }
        }

        WorkerStatistics statistics = new WorkerStatistics(
                user.getUsername(),
                clientNumber,
                num,
                profit,
                avr.getWeight1() * clientNumber + avr.getWeight2() * num + avr.getWeight3() * profit,
                null
        );


        return
                new WorkerStatistics(
                        user.getUsername(),
                        clientNumber,
                        num,
                        profit,
                        avr.getWeight1() * clientNumber + avr.getWeight2() * num + avr.getWeight3() * profit,
                        null
                );
    }

    @Override
    public List<WorkerStatistics> getSomeWorker(SpecificWorker specificWorker) {
        Average avr = new Average(specificWorker.getWeight1(), specificWorker.getWeight2(), specificWorker.getWeight3());
        List<WorkerStatistics> workerStatisticsArrayList = new ArrayList<>();

        String username = specificWorker.getWorkerName();

        QueryWrapper<UserEntity> qw = new QueryWrapper<>();
        qw.like("username", username);
        qw.eq("is_delete", 0);
        qw.eq("role_name", "销售员");

        List<UserEntity> userList = userMapper.selectList(qw);

        if (userList.isEmpty())
            return null;

        for (UserEntity user : userList) {
            WorkerStatistics statistics = getSpecificWorker(avr, user);
            statistics.setValue(statistics.getWorkerName());
            workerStatisticsArrayList.add(statistics);
        }

        return workerStatisticsArrayList;
    }

    @Override
    public GoodsStatistics getSpecificGoods(GoodsEntity goods) {
        QueryWrapper<StoreEntity> qw = new QueryWrapper<>();
        qw.eq("is_delete", 0);
        qw.eq("goods_id", goods.getGoodsId());

        List<StoreEntity> storeList = storeMapper.selectList(qw);

        int storeNum = 0;
        for (StoreEntity store : storeList) {
            storeNum += store.getGoodsNumber();
        }

        QueryWrapper<OrderGoodsMapEntity> qw1 = new QueryWrapper<>();
        qw1.eq("is_delete", 0);
        qw1.eq("goods_id", goods.getGoodsId());
        List<OrderGoodsMapEntity> mapList = orderGoodsMapMapper.selectList(qw1);

        int outNum = 0;
        double profit = 0;
        for (OrderGoodsMapEntity map : mapList) {
            Long orderId = map.getOrderId();
            OrderEntity order = orderMapper.selectById(orderId);
            Integer inOut = order.getInOut();


            //销售
            if (inOut == 1) {
                outNum += map.getGoodsNumber();
                profit += map.getGoodsNumber() * (map.getSinglePrice() - goods.getStockPrice());
            }
            if (inOut == 0) {
                outNum -= map.getGoodsNumber();
                profit -= map.getGoodsNumber() * (map.getSinglePrice() - goods.getStockPrice());
            }
        }

        int inNum = outNum + storeNum;
        double unSoldMoney = storeNum * goods.getStockPrice();


        return new GoodsStatistics(goods.getGoodsName(), inNum, outNum, storeNum, unSoldMoney, profit, null);


    }

    @Override
    public List<GoodsStatistics> getGoodsStatistics() {
        ArrayList<GoodsStatistics> list = new ArrayList<>();

        QueryWrapper<GoodsEntity> qw = new QueryWrapper<>();
        qw.eq("is_delete", 0);
        List<GoodsEntity> goodsList = goodsMapper.selectList(qw);

        for (GoodsEntity goods : goodsList) {
            list.add(getSpecificGoods(goods));
        }


        return list;
    }

    @Override
    public List<GoodsStatistics> getSomeGoods(String goodsName) {
        List<GoodsStatistics> list = new ArrayList<>();

        QueryWrapper<GoodsEntity> qw = new QueryWrapper<>();
        qw.eq("is_delete", 0);
        qw.like("goods_name", goodsName);

        List<GoodsEntity> goodsList = goodsMapper.selectList(qw);

        if (goodsList.isEmpty())
            return null;

        for (GoodsEntity goods : goodsList) {
            GoodsStatistics specificGoods = getSpecificGoods(goods);
            specificGoods.setValue(specificGoods.getGoodsName());
            list.add(specificGoods);
        }

        return list;
    }
}
